<template>
  <view class="signa">
    <view class="header">{{ target }}</view>
    <view class="btn">
      <view class="cancel-btn" @click="clear"> 重写 </view>
      <view class="save-btn" @click="commit"> 确认 </view>

      <view v-if="isList" class="select-trainer-text">
        <view>选择{{ title }}:</view>
        <view @click="listSelect = !listSelect" class="select-trainer">
          <view>{{
            listActiveIndex == -1 ? "空" : list[listActiveIndex].name
          }}</view>
          <view :class="{ i: true, iselect: listSelect }">></view>
          <view :class="{ listselect: true, listselectactive: listSelect }">
            <div
              class="item"
              v-for="(item, index) in list"
              :key="index"
              @click="listItemClick(index)"
            >
              {{ item.name }}
            </div>
          </view>
        </view>
      </view>
    </view>
    <canvas
      class="canvas"
      disable-scroll="true"
      :width="canvasWidth"
      :height="canvasHieght"
      :style="{ width: width, height: height }"
      canvas-id="designature"
      @touchstart="starts"
      @touchmove="moves"
      @touchend="end"
    >
      <canvas
        v-if="isTrim"
        :style="{
          width: trimWidth + 'px',
          height: trimHeight + 'px',
          opacity: 0,
        }"
        :width="trimWidth"
        :height="trimHeight"
        canvas-id="designature-trim"
      ></canvas>
    </canvas>
    <Toast ref="toastRef" />
  </view>
</template>
<script>
import { exitPage, trimImage } from '@/common/index/utils/common'
import { lastSignData } from "@/common/index/config/data"
import { showToast, toastRef } from '@/common/index/utils/toast'
import Toast from '@/components/index/Toast.vue'
import { clientEvent } from '@/common/index/utils/ClientEvent'
import { KEY_BACK } from '@/common/index/config/Event'
export default {
  components: {},
  data () {
    return {
      dom: null,
      line: [],
      radius: 0,
      width: '0px',
      height: '0px',
      target: undefined,
      uuid: undefined,
      canvasWidth: 0,
      canvasHieght: 0,
      trimWidth: 0,
      trimHeight: 0,
      isTrim: false,
      isRectangle: false,
      isDraw: false,
      isSelectTrainer: false,
      title: '',
      isList: false,
      listSelect: false,
      list: [{
        id: 1,
        name: "213"
      }, {
        id: 2,
        name: "21233"
      }, {
        id: 3,
        name: "rw213"
      }],
      listActiveIndex: -1
    }
  },
  onLoad ({ title, uuid, isRectangle, selectTrainer }) {
    if (title) {
      this.target = "请" + title + "签名"
      this.title = title
    } else {
      this.target = "请签名"
    }
    if (uuid) {
      this.uuid = uuid
    }
    if (selectTrainer != "false") {
      this.isList = true
    }
    this.list = this.$store.state.trainers || []
    this.isRectangle = isRectangle == "true"
  },
  computed: {

  },
  created () {
    uni.getSystemInfo({
      success: (res) => {
        this.canvasWidth = res.windowWidth * 19 / 20
        this.canvasHieght = this.isRectangle ? this.canvasWidth : (res.windowWidth * 15 / 40)
        this.width = this.canvasWidth + 'px'
        this.height = this.canvasHieght + 'px'
        this.trimHeight = 200
        this.trimWidth = 200
      }
    })
    this.dom = uni.createCanvasContext('designature', this)

  },
  methods: {
    end (e) {

    },
    distance (a, b) {
      let x = b.x - a.x
      let y = b.y - a.y
      return Math.sqrt(x * x + y * y)
    },
    // 开始
    starts (e) {
      this.line.push({
        points: [{
          time: new Date().getTime(),
          x: e.touches[0].x,
          y: e.touches[0].y,
          dis: 0
        }]
      })
      let currentPoint = {
        x: e.touches[0].x,
        y: e.touches[0].y
      }
      this.currentPoint = currentPoint
      this.drawer(this.line[this.line.length - 1])
    },
    // 滑动
    moves (e) {
      let point = {
        x: e.touches[0].x,
        y: e.touches[0].y
      }
      this.lastPoint = this.currentPoint,
        this.currentPoint = point
      this.line[this.line.length - 1].points.push({
        time: new Date().getTime(),
        x: e.touches[0].x,
        y: e.touches[0].y,
        dis: this.distance(this.currentPoint, this.lastPoint)
      })
      this.drawer(this.line[this.line.length - 1])
    },
    // 书写
    drawer (item) {
      let x1, x2, y1, y2, len, radius, r, cx, cy, t = 0.5,
        x, y
      var time = 0
      if (item.points.length > 2) {
        let lines = item.points[item.points.length - 3]
        let line = item.points[item.points.length - 2]
        let end = item.points[item.points.length - 1]
        x = line.x
        y = line.y
        x1 = lines.x
        y1 = lines.y
        x2 = end.x
        y2 = end.y
        var dis = 0
        time = (line.time - lines.time) + (end.time - line.time)
        dis = line.dis + lines.dis + end.dis
        var dom = this.dom
        var or = Math.min(time / dis * this.linePressure + this.lineMin, this.lineMax)
        cx = (x - (Math.pow(1 - t, 2) * x1) - Math.pow(t, 2) * x2) / (2 * t * (1 - t))
        cy = (y - (Math.pow(1 - t, 2) * y1) - Math.pow(t, 2) * y2) / (2 * t * (1 - t))
        dom.setLineCap('round')
        dom.beginPath()
        dom.setStrokeStyle('black')
        dom.setLineWidth(5)
        dom.moveTo(x1, y1)
        dom.quadraticCurveTo(cx, cy, x2, y2)
        dom.stroke()
        dom.draw(true)
        this.isDraw = true
      }
    },
    // 清除
    clear () {
      this.dom.clearRect(0, 0, 1000, 1000)
      this.dom.draw()
      this.isDraw = false
    },
    save (canvasId) {
      uni.canvasToTempFilePath({
        canvasId: canvasId || 'designature-trim',
        fileType: 'png',
        quality: 1, //图片质量
        success: (res) => {
          lastSignData.value = res.tempFilePath
          if (this.uuid) {
            lastSignData.uuid = this.uuid

          }
          if (this.isList) {
            lastSignData.signid = this.list[this.listActiveIndex].id
          }
          exitPage()
        },
        fail (e) {
          showToast("保存错误")
        },
        complete: () => {
          this.isTrim = false
        }
      }, this)
    },
    //裁剪
    trim () {
      uni.canvasGetImageData({
        canvasId: "designature",
        x: 0,
        y: 0,
        width: this.canvasWidth,
        height: this.canvasHieght,
        success: (data) => {
          const result = trimImage(data)
          if (result == null) {
            showToast("签名", "不能为空")
            return
          }
          this.trimWidth = result.w
          this.trimHeight = result.h
          this.isTrim = true
          uni.canvasGetImageData({
            canvasId: "designature",
            width: result.w,
            height: result.h,
            x: result.x,
            y: result.y,
            success: (data2) => {
              setTimeout(() => {
                uni.canvasPutImageData({
                  canvasId: "designature-trim",
                  width: this.trimWidth,
                  height: this.trimHeight,
                  x: 0,
                  y: 0,
                  data: data2.data,
                  success: () => {
                    this.save()
                  },
                  fail: e => {
                    showToast(e.toString(), "")
                  }
                })
              }, 200)
            }
          })
        }
      })
    },
    commit () {
      if (!this.isDraw) {
        showToast("请签名", "不可以为空")
        return
      }
      if (this.isList && this.listActiveIndex == -1 && this.list.length != 0) {
        showToast("请输入的" + this.title + "姓名", "不可以为空")
        return
      }
      this.save('designature')
    },
    backpress () {
      choice("退出", "你要退出吗？", true, () => plus.runtime.quit())
    },
    mountEvent () {
      clientEvent.on(KEY_BACK, this.backpress, this)
    },
    unmountEvent () {
      clientEvent.off(KEY_BACK, this.backpress, this)
    },
    listItemClick (index) {
      this.listActiveIndex = index
    }
  },
  components: {
    Toast
  },
  mounted () {
    toastRef.value = this.$refs.toastRef
  },
  onShow () {
    this.mountEvent()
  },
  onHide () {
    this.unmountEvent()
  },
  onUnload () {
    this.unmountEvent()
  }

}
</script>

<style scoped lang="scss">
.signa {
  position: relative;
  overflow: hidden;
  background-color: #f1efef;
  height: 100vh;
  width: 100vw;

  .canvas {
    background-color: #ffffff;
    position: absolute;
    z-index: 5;
    left: 3vw;
    top: 13vw;
    border: 1px solid #d6d6d6;
  }

  .btn {
    height: 12vw;
    width: 100vw;
    position: fixed;

    font-size: 32rpx;
    display: flex;
    z-index: 6;
    bottom: 0;
    justify-content: center;

    .cancel-btn {
      width: 20vh;
      flex: 1;
      border: 1rpx solid #a9a1a1;
      color: #666;
      height: 10vw;
      border-radius: 3px;
      text-align: center;
      font-size: 5vw;
      background-color: #f1efef;
      border-radius: 4vw;
      margin: 0 3vw;
    }

    .save-btn {
      z-index: 6;
      flex: 1;
      background-color: #007aff;
      width: 20vh;
      height: 10vw;
      border-radius: 3px;
      border: 1rpx solid #007aff;
      color: #fff;
      font-size: 5vw;
      border-radius: 4vw;
      text-align: center;
      margin: 0 3vw;
    }
    .select-trainer-text {
      position: absolute;
      font-size: 4vw;
      top: -10vw;
      left: 10vw;
    }
    .select-trainer {
      padding-left: 2vw;
      position: absolute;
      width: 30vw;
      font-size: 4vw;
      left: 22vw;
      top: 0;
      background-color: #e4e4e4;
      border: 0.3vw solid rgb(110, 110, 110);
      border-radius: 1vw;
      height: 7vw;
      .i {
        position: absolute;
        transform: translate(-50%, -50%);
        top: 50%;
        right: 5%;
        transition: 0.2s;
      }
      .iselect {
        transform: translate(-50%, -50%) rotate(-90deg);
      }
      .listselect {
        position: absolute;
        width: 100%;
        min-height: 10vw;
        left: 0;
        bottom: 105%;
        border: 0.3vw solid rgb(110, 110, 110);
        transition: 0.2s;
        transform: scaleY(0);
        transform-origin: 0 100%;
        .item {
          width: 100%;
          border: 0.3vw solid rgb(110, 110, 110);
          height: 7vw;
          border-radius: 1vw;
          background-color: white;
        }
      }
      .listselectactive {
        transform: scaleY(1);
      }
    }
  }
}
</style>